package org.fyp.synchrona.moodle.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.fyp.synchrona.core.info.impl.ICommonDataObject;
import org.fyp.synchrona.moodle.communication.Communication;
import org.fyp.synchrona.moodle.service.util.NewData;
import org.fyp.synchrona.moodle.service.util.OldData;
import org.fyp.synchrona.util.IUpdate;

public class Updater {
	
	public String userName;
	
	public String password;
	
	Communication com;
	
	OldData OldDataObj;
	
	NewData newDataObj;
	
	NewDataProcessor ndp;
	
	OldDataProcessor odp;
	
	static final Logger logger = Logger.getLogger(Updater.class);
	
	public Updater(String userName, String password){
		this.userName = userName;
		this.password = password;
		com = new Communication(userName,password);
		OldDataObj = new OldData();
		newDataObj = new NewData();
		odp = new OldDataProcessor(OldDataObj);
		ndp = new NewDataProcessor(OldDataObj,newDataObj);
	}
	
	public void startUpdate(IUpdate updateObj){
		logger.info("[MOODLE] update Type ::"+updateObj.getUpdateType());
		try {
			if(updateObj.getUpdateType()=="PROFILE"){
				logger.info("[MOODLE] --------------------Moodle Profile Update----------------------------------");
				updateService(updateObj.getCdo());
			}
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	private void updateService(ICommonDataObject cdo) throws ClientProtocolException, IOException {
		HttpPost httpost = new HttpPost(com.getLoginURL());
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	    nvps.add(new BasicNameValuePair("username", com.getUserName()));
	    nvps.add(new BasicNameValuePair("password", com.getPassword()));
	    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = com.getHttpClient().execute(httpost);
        HttpEntity entity = response.getEntity();
        logger.info("[MOODLE]Login form post: " + response.getStatusLine());
        if (entity != null) {
        	//System.out.println("Logged in page: "+EntityUtils.toString(entity));
            entity.consumeContent();
        }
        HttpGet httpget = new HttpGet("http://localhost/moodle/user/editadvanced.php");
        response = com.getHttpClient().execute(httpget);
        entity = response.getEntity();
        
        String sesskey ="";
        if (entity != null) {
        	String editPage = EntityUtils.toString(entity);
        	//System.out.println(editPage);
			odp.retriveOldParameters(editPage);
			entity.consumeContent();
        }
        ndp.createUpdateObj(cdo);
        updateMoodle(ndp.newDataObj);
	}
        public void updateMoodle(NewData newDataObj) {
    		
            HttpPost profileEdit   = new HttpPost("http://localhost/moodle/user/editadvanced.php");
            MultipartEntity reqEntity = new MultipartEntity();

            try {
            	reqEntity.addPart("MAX_FILE_SIZE", new StringBody("16777216"));
                reqEntity.addPart("id", new StringBody("2") );
                reqEntity.addPart("course", new StringBody("1"));
                reqEntity.addPart("mform_showadvanced_last", new StringBody("") );
                reqEntity.addPart("sesskey", new StringBody(newDataObj.getSessionKey()) ); //get session key
                reqEntity.addPart("_qf__user_editadvanced_form", new StringBody("1") );
                //reqEntity.addPart("mform_showadvanced", new StringBody("Show Advanced") );
                reqEntity.addPart("username", new StringBody("admin123"));
                logger.info("[MOODLE] username ::"+newDataObj.getusername());
                if(newDataObj.getusername()==null){
                	reqEntity.addPart("firstname", new StringBody(newDataObj.getfirstname()) );
                }else{
                	reqEntity.addPart("firstname", new StringBody(newDataObj.getusername()) );
                }
                reqEntity.addPart("lastname", new StringBody(newDataObj.getlastname()));
                
                reqEntity.addPart("email", new StringBody(newDataObj.getemail()) );
               
                reqEntity.addPart("maildisplay", new StringBody("1") );
                reqEntity.addPart("emailstop", new StringBody("1") );
                reqEntity.addPart("mailformat", new StringBody("1") );
                reqEntity.addPart("maildigest", new StringBody("1") );
                reqEntity.addPart("autosubscribe", new StringBody("1") );
                reqEntity.addPart("trackforums", new StringBody("0") );
                reqEntity.addPart("htmleditor", new StringBody("0") );
                reqEntity.addPart("ajax", new StringBody("0") );
                reqEntity.addPart("screenreader", new StringBody("1") );
                reqEntity.addPart("city", new StringBody(newDataObj.getcity()) );
                reqEntity.addPart("country", new StringBody("LK"));
                reqEntity.addPart("timezone", new StringBody("5.5") );
                reqEntity.addPart("description", new StringBody(newDataObj.getdescription()) );
                reqEntity.addPart("lang", new StringBody("en_utf8") );
                reqEntity.addPart("interests", new StringBody(newDataObj.getinterests()) );
                reqEntity.addPart("imagealt", new StringBody(""));
                reqEntity.addPart("mform_showadvanced", new StringBody("") );
                reqEntity.addPart("url", new StringBody(newDataObj.geturl()));
                reqEntity.addPart("icq", new StringBody("") );
                reqEntity.addPart("skype", new StringBody("") );
                reqEntity.addPart("aim", new StringBody("") );
                reqEntity.addPart("yahoo", new StringBody("") );
                reqEntity.addPart("msn", new StringBody(""));
                reqEntity.addPart("idnumber", new StringBody("") );
                reqEntity.addPart("institution", new StringBody("") );
                reqEntity.addPart("department", new StringBody("") );
                reqEntity.addPart("phone1", new StringBody(newDataObj.getphone1()) );
                reqEntity.addPart("phone2", new StringBody(newDataObj.getphone2()) );
                reqEntity.addPart("address", new StringBody(newDataObj.getaddress()) );
                reqEntity.addPart("submitbutton", new StringBody("Update profile") );       
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
           


            profileEdit.setEntity(reqEntity);
            HttpResponse response = null;
            try {
    			response = com.getHttpClient().execute(profileEdit);
    		} catch (ClientProtocolException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
            HttpEntity entity = response.getEntity();
            logger.info("[MOODLE] Profile update ::" + response.getStatusLine());
            if (entity != null) {
            	//System.out.println("Profile edit page: "+EntityUtils.toString(entity));
                try {
    				entity.consumeContent();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
            }

            com.getHttpClient().getConnectionManager().shutdown();    
                   
     		
    		
    	}
	
}
